﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BasicClass;

namespace DealPLC
{
    /// <summary>
    /// WinCheckReg.xaml 的交互逻辑
    /// </summary>
    public partial class WinCheckReg : BaseWindow
    {
        #region 窗体单实例
        private static WinCheckReg g_WinCheckReg = null;
        public static WinCheckReg GetWinInst(out bool blNew)
        {
            blNew = false;
            try
            {
                if (g_WinCheckReg == null)
                {
                    blNew = true;
                    g_WinCheckReg = new WinCheckReg();
                }
                return g_WinCheckReg;
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError("WinCheckReg", ex);
                return null;
            }
        }

        public static WinCheckReg GetWinInst()
        {
            try
            {
                return g_WinCheckReg;
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError("WinCheckReg", ex);
                return null;
            }
        }
        #endregion 窗体单实例

        #region 定义
        public List<CheckReg> CheckReg_L = new List<CheckReg>();
        #endregion 定义

        #region 初始化
        public WinCheckReg()
        {
            InitializeComponent();

            NameClass = "WinCheckReg";

            //刷新显示
            LogicPLC.L_I.RefreshRegValue_event += L_I_RefreshRegValue_event;
        }

        public void Init()
        {
            try
            {
                if (CheckReg.C_I.CheckReg_L.Count == 0)
                {
                    CheckReg.C_I.AddValue(null);
                }
                ShowPar_Invoke();
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }
        #endregion 初始化

        #region 读写寄存器
        /// <summary>
        /// 读取寄存器值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReadReg_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnReadReg.Content = "读寄存器";

                string reg = txtReadReg.Text.Trim();
                if (reg == "")
                {
                    return;
                }
                if (!reg.EndsWith("\n"))
                {
                    reg += "\n";
                }
                string[] regs = reg.Split('\n');
                int num = 1;
                if (regs.Length > 2)
                {
                    num = 2;
                }
                int[] value = null;
                bool blResult = LogicPLC.L_I.ReadBlockReg(reg, num, "btnReadReg_Click", out value);
                string strValue = "";
                if (value.Length == 1)
                {
                    strValue = value[0].ToString();
                }
                else
                {
                    strValue = (value[0] * 65536 + value[1]).ToString();
                }
                txtReadValue.Text = strValue;

                if (blResult)
                {
                    btnReadReg.RefreshDefaultColor("读取成功", true);
                }
                else
                {
                    btnReadReg.RefreshDefaultColor("读取失败", false);
                }
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }


        /// <summary>
        /// 写入寄存器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWriteReg_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnWriteReg.Content = "写寄存器";

                string reg = txtWriteReg.Text.Trim();
                string strValue = txtWriteValue.Text.Trim();
                if (reg == ""
                    || strValue=="")
                {
                    return;
                }

                if (!reg.EndsWith("\\n"))
                {
                    reg += "\\n";
                }
                string[] regs = reg.Replace("\\n","\n").Split('\n');
                int num = 1;
                if (regs.Length > 2)
                {
                    num = 2;
                }

                int[] value = new int[num];

                bool blResult = false;
                

                 if (value.Length == 1)//写入单个寄存器
                {
                    int init = Convert.ToInt32(strValue);
                    value[0] = LogicPLC.L_I.ConvertWriteData(init)[0];
                    blResult = LogicPLC.L_I.WriteBlockReg(reg, num, value, "btnWriteReg_Click");
                }
                else
                {
                    int init = Convert.ToInt32(strValue);
                    value[0] = LogicPLC.L_I.ConvertWriteData(init)[0];
                    value[1] = LogicPLC.L_I.ConvertWriteData(init)[1];
                    blResult = LogicPLC.L_I.WriteBlockReg(reg, num, value, "btnWriteReg_Click");                  
                }

                if (blResult)
                {
                    btnWriteReg.RefreshDefaultColor("写入成功", true);
                }
                else
                {
                    btnWriteReg.RefreshDefaultColor("写入失败", false);
                }
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }
        #endregion 读写寄存器

        /// <summary>
        /// 双击列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgReg_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if(dgReg.IsMouseOver)
                {
                    txtWriteReg.Text = CheckReg.C_I.CheckReg_L[dgReg.SelectedIndex].NameReg;
                }                
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }

        #region 显示
        /// <summary>
        /// PLC寄存器值发生变化
        /// </summary>
        private void L_I_RefreshRegValue_event()
        {
            ShowPar_Invoke();
        }


        public override void ShowPar()
        {
            try
            {
                dgReg.ItemsSource = CheckReg.C_I.CheckReg_L;
                dgReg.Items.Refresh();
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }

        public new void Show()
        {
            this.Visibility = Visibility.Visible;
            base.Show();
        }
        #endregion 显示

        #region 关闭
        private void BaseWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
            e.Cancel = true;
        }
        #endregion 关闭

       
    }

    public class CheckReg : BaseClass
    {
        #region 静态类实力
        public static CheckReg C_I = new CheckReg();
        #endregion 静态类实力

        #region 定义
        public string NameReg { set; get; }
        public string Time { set; get; }
        public double ValueCur { set; get; }
        public double Old1 { set; get; }
        public double Old2 { set; get; }
        public double Old3 { set; get; }
        public double Old4 { set; get; }
        public double Old5 { set; get; }
        public double Old6 { set; get; }
        public double Old7 { set; get; }
        public double Old8 { set; get; }
        public double Old9 { set; get; }
        public double Old10 { set; get; }
        public double Old11 { set; get; }
        public double Old12 { set; get; }

        public bool BlChange//值是不是发生变化
        {
            get
            {
                if (ValueCur != Old1)//值如果发生变化
                {
                    return true;
                }
                return false;
            }
            set
            {

            }
        }

        /// <summary>
        /// 列表row颜色
        /// </summary>
        public SolidColorBrush BrCell
        {
            get
            {
                SolidColorBrush colorSpeet = Brushes.Black;
                if (BlChange)
                {
                    colorSpeet = Brushes.Red;
                }
                else
                {
                    colorSpeet = Brushes.White;
                }
                return colorSpeet;
            }
        }

        public List<CheckReg> CheckReg_L = new List<CheckReg>();
        public List<double[]> Value_L = new List<double[]>();
        #endregion 定义

        /// <summary>
        /// PLC值加入列表
        /// </summary>
        /// <param name="intValue"></param>
        public void AddValue(int[] intValue)
        {
            try
            {
                if (intValue == null)
                {
                    intValue = new int[ParSetPLC.P_I.IntNumCycReg];
                }
                double[] valueNew = new double[RegMonitor.R_I.NumReg];

                //单寄存器的触发信号,将读取的数据转换到触发和读值
                for (int i = 0; i < RegMonitor.R_I.NumTrigger; i++)
                {
                    valueNew[i] = intValue[i];
                }
                //读值保留，需要转换一下
                for (int i = 0; i < (intValue.Length - RegMonitor.R_I.NumTrigger) / 2; i++)
                {
                    valueNew[i + RegMonitor.R_I.NumTrigger] = LogicPLC.L_I.ConvertReadData(intValue[2 * i + RegMonitor.R_I.NumTrigger], intValue[2 * i + 1 + RegMonitor.R_I.NumTrigger]);
                }

                if (Value_L.Count < 10)
                {
                    for (int i = Value_L.Count; i < 10; i++)
                    {
                        int[] value = new int[ParSetPLC.P_I.IntNumCycReg];
                        Value_L.Add(valueNew);
                    }
                }
                else if (Value_L.Count > 10)//移除第一个
                {
                    Value_L.RemoveAt(0);
                }

                List<CheckReg> checkReg_L = new List<CheckReg>();

                Value_L.Add(valueNew);
                int count = Value_L.Count;

                for (int i = 1; i < RegMonitor.R_I.NumReg; i++)
                {
                    CheckReg reg = new CheckReg();

                    reg.No = i;
                    reg.NameReg = RegMonitor.R_I[i].NameReg;
                    reg.ValueCur = Value_L[10][i];
                    reg.Old1 = Value_L[9][i];
                    reg.Old2 = Value_L[8][i];
                    reg.Old3 = Value_L[7][i];
                    reg.Old4 = Value_L[6][i];
                    reg.Old5 = Value_L[5][i];
                    reg.Old6 = Value_L[4][i];
                    reg.Old7 = Value_L[3][i];
                    reg.Old8 = Value_L[2][i];
                    reg.Old9 = Value_L[1][i];
                    reg.Old10 = Value_L[0][i];
                    reg.Annotation = RegMonitor.R_I[i].Annotation;

                    checkReg_L.Add(reg);
                }

                CheckReg_L = checkReg_L;
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }

        /// <summary>
        /// 导入没有心跳的本地数据
        /// </summary>
        /// <param name="intValue"></param>
        public void AddValue_WithoutHeart(int[] intValue)
        {
            try
            {
                if (intValue == null)
                {
                    intValue = new int[ParSetPLC.P_I.IntNumCycReg];
                }
                double[] valueNew = new double[RegMonitor.R_I.NumReg];

                //单寄存器的触发信号,将读取的数据转换到触发和读值
                for (int i = 0; i < RegMonitor.R_I.NumTrigger; i++)
                {
                    valueNew[i] = intValue[i];
                }
                //读值保留，需要转换一下
                for (int i = 0; i < (intValue.Length - RegMonitor.R_I.NumTrigger) / 2; i++)
                {
                    valueNew[i + RegMonitor.R_I.NumTrigger] = LogicPLC.L_I.ConvertReadData(intValue[2 * i + RegMonitor.R_I.NumTrigger], intValue[2 * i + 1 + RegMonitor.R_I.NumTrigger]);
                }

                if (Value_L.Count < 10)
                {
                    for (int i = Value_L.Count; i < 10; i++)
                    {
                        int[] value = new int[ParSetPLC.P_I.IntNumCycReg];
                        Value_L.Add(valueNew);
                    }
                }
                else if (Value_L.Count > 10)//移除第一个
                {
                    Value_L.RemoveAt(0);
                }

                List<CheckReg> checkReg_L = new List<CheckReg>();

                Value_L.Add(valueNew);
                int count = Value_L.Count;

                for (int i = 1; i < RegMonitor.R_I.NumReg; i++)
                {
                    CheckReg reg = new CheckReg();
                    reg.No = i;
                    reg.NameReg = RegMonitor.R_I[i].NameReg;

                    reg.ValueCur = Value_L[10][i - 1];//数据中没有心跳
                    reg.Old1 = Value_L[9][i - 1];
                    reg.Old2 = Value_L[8][i - 1];
                    reg.Old3 = Value_L[7][i - 1];
                    reg.Old4 = Value_L[6][i - 1];
                    reg.Old5 = Value_L[5][i - 1];
                    reg.Old6 = Value_L[4][i - 1];
                    reg.Old7 = Value_L[3][i - 1];
                    reg.Old8 = Value_L[2][i - 1];
                    reg.Old9 = Value_L[1][i - 1];
                    reg.Old10 = Value_L[0][i - 1];

                    reg.Annotation = RegMonitor.R_I[i].Annotation;

                    checkReg_L.Add(reg);
                }

                CheckReg_L = checkReg_L;
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }
    }
}
